// 详细页面控制器
angular.module('details.controller', ['details.service'])
  .controller('DetailsCtrl', function($scope,GlobalVariable,$stateParams,$ionicHistory,IndexdbJs) {

    // 购物车徽章位置显示的数量
    $scope.obj_cartCount = {
      count: 0
    }

    // 视图事件
    $scope.$on('$ionicView.beforeEnter', function (e) {

      IndexdbJs.getAll('cart',function(data){
        var count=0;
        for(var i =0;i<data.length;i++){
          count=count+data[i].number;
        }
        $scope.obj_cartCount.count=count;
        // 在异步操作中给双向数据绑定模型赋值，不能及时监听到，所以我们需要手动监听他变化一下
        $scope.$apply();

      },null)


    });



    //$stateParams.productId;
    // 通过后台获取到的商品详细信息数据
    $scope.obj_goodsInfo = {
      goodsId: "200067",
      description: "若昕 韩版睡衣女冬法兰绒家居服加厚珊瑚绒女人卡通甜美睡衣秋冬套装 66651K 女 M",
      prise: "66",
      picture: [],
      src: "",
      isFork: false,
      colorGroup: [{name: "红色", value: "red"}, {name: "蓝色", value: "blue"}],
      sizeGroup: [{name: "s", value: "s"}, {name: "m", value: "m"}, {name: "l", value: "l"}]
    };



    // 用户选择信息
    $scope.obj_goodsDetailInfo = {
      goodsId: $scope.obj_goodsInfo.goodsId,
      isFork: $scope.obj_goodsInfo.isFork,
      description: $scope.obj_goodsInfo.description,
      src: $scope.obj_goodsInfo.src,
      prise: $scope.obj_goodsInfo.prise,
      color: "",
      size: "",
      number: 1
    }

    // 加入数据到购物车方法
    $scope.func_addToCart=function(){

      var obj_newData={};
      // 硬拷贝方法
      angular.copy($scope.obj_goodsDetailInfo,obj_newData);
      // 从新改变编号
      obj_newData.goodsId =obj_newData.goodsId + "-" + obj_newData.color + "-" + obj_newData.size;

      IndexdbJs.get(obj_newData.goodsId,"cart",function(data){
         if(data){
           obj_newData.number=obj_newData.number+data.number;
           IndexdbJs.update('cart',obj_newData,function(){
             $scope.obj_cartCount.count=$scope.obj_cartCount.count+$scope.obj_goodsDetailInfo.number;
             $scope.$apply();
           },null);

         }else{
           IndexdbJs.add('cart',obj_newData,function(){
             $scope.obj_cartCount.count=$scope.obj_cartCount.count+$scope.obj_goodsDetailInfo.number;
             $scope.$apply();
           },null);
         }

      },null)

    }


    // 数量加1
    $scope.func_jia1 = function () {
      $scope.obj_goodsDetailInfo.number++;
    }

    // 数量减1
    $scope.func_jian1 = function () {
      if ($scope.obj_goodsDetailInfo.number != 1) {
        $scope.obj_goodsDetailInfo.number--;
      }
    }


    $scope.func_goBack=function(){
      $ionicHistory.goBack();
    }



  })
